package com.time.auth.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.time.auth.common.enums.AuthPermissionShowEnum;
import com.time.auth.common.enums.AuthPermissionStatusEnum;
import com.time.auth.common.enums.IsDeletedFlagEnum;
import com.time.auth.common.utils.CollectionUtils;
import com.time.auth.domain.constants.AuthConstant;
import com.time.auth.domain.constants.ExceptionCode;
import com.time.auth.domain.convent.AuthPermissionBOConverter;
import com.time.auth.domain.entity.AuthPermissionBO;
import com.time.auth.domain.exception.NotFoundDomainException;
import com.time.auth.domain.redis.RedisUtil;
import com.time.auth.domain.service.AuthPermissionDomainService;
import com.time.auth.infra.basic.entity.AuthPermission;
import com.time.auth.infra.basic.entity.AuthRole;
import com.time.auth.infra.basic.entity.AuthRolePermission;
import com.time.auth.infra.basic.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限服务领域层接口实现类
 *
 * @author: HuangQi
 * @date: Created in 11:03 2025/9/24
 * @description: 权限服务领域层接口实现类
 */
@Service("authPermissionDomainService")
@Slf4j
public class AuthPermissionDoaminServiceImpl implements AuthPermissionDomainService {

    @Autowired
    private AuthUserService authUserService;

    @Autowired
    private AuthAdminUserService authAdminUserService;

    @Autowired
    private AuthRoleService authRoleService;

    @Autowired
    private AuthUserRoleService authUserRoleService;

    @Autowired
    private AuthRolePermissionService authRolePermissionService;

    @Autowired
    private AuthPermissionService authPermissionService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Boolean add(AuthPermissionBO authPermissionBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthPermissionDomainServiceImpl.add.bo:{}", JSON.toJSONString(authPermissionBO));
        }

        // 参数转换
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBoToEntity(authPermissionBO);
        authPermission.setStatus(AuthPermissionStatusEnum.OPEN.getCode());
        authPermission.setShow(AuthPermissionShowEnum.UN_SHOW.getCode());
        authPermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        // 调用 service
        Integer count = authPermissionService.insert(authPermission);

        // 返回结果
        return count > 0;
    }

    @Override
    public Boolean update(AuthPermissionBO authPermissionBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthPermissionDomainServiceImpl.update.bo:{}", JSON.toJSONString(authPermissionBO));
        }

        // 参数转换
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBoToEntity(authPermissionBO);

        // 调用 service
        Integer count = authPermissionService.update(authPermission);

        // 返回结果
        return count > 0;
    }

    @Override
    @Transactional
    public Boolean delete(AuthPermissionBO authPermissionBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthPermissionDomainServiceImpl.delete.bo:{}", JSON.toJSONString(authPermissionBO));
        }

        // 参数转换
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBoToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());

        // 调用 service
        Integer count = authPermissionService.update(authPermission);

        // 删除角色权限关联表中的数据
        if (count > 0) {
            AuthRolePermission authRolePermission = new AuthRolePermission();
            authRolePermission.setPermissionId(authPermission.getId());
            authRolePermission.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
            int update_count = authRolePermissionService.updateByPermissionId(authRolePermission);
        }

        return count > 0;
    }

    @Override
    public List<String> getPermission(String userName, String userType) {
        if (log.isInfoEnabled()) {
            log.info("AuthPermissionDomainServiceImpl.getPermission.userName:{}, userType:{}", userName, userType);
        }

        String permissionKey = redisUtil.buildKey(AuthConstant.AUTH_PERMISSION_USER_PREFIX, userName);
        String permissionValue = redisUtil.get(permissionKey);
        List<String> authList = new LinkedList<>();
        if (StringUtils.isBlank(permissionValue)) {
            // 如果从redis中拿到的value为空,查询数据库
            Long id = null;
            if (AuthConstant.ADMIN_USER_TYPE.equals(userType)) {
                // 从管理员用户表中获取用户id
                id = authAdminUserService.queryByUserName(userName).getAdminId();
            } else if (AuthConstant.NORMAL_USER_TYPE.equals(userType)) {
                // 从普通用户表中获取用户id
                id = authUserService.queryByUserName(userName).getUserId();
            }
            if (id == null) {
                throw new NotFoundDomainException(ExceptionCode.USER_NOT_FOUND, "用户不存在");
            }

            // 根据用户id查询角色id列表
            List<Long> roleIdList = authUserRoleService.queryByUserId(id, userType);
            // 根据角色id列表查询角色信息
            List<AuthRole> roleList = authRoleService.queryByRoleList(roleIdList);
            // 将角色信息存入redis
            if (CollectionUtils.isEmpty(roleList)) {
                throw new NotFoundDomainException(ExceptionCode.ROLE_NOT_FOUND, "该用户未分配角色");
            }
            String roleKey = redisUtil.buildKey(AuthConstant.AUTH_ROLE_USER_PREFIX, userName);
            redisUtil.set(roleKey, new Gson().toJson(roleList));

            // 通过角色id列表查询权限id列表
            List<Long> permissionIdList = authRolePermissionService.queryByRoleIdList(roleIdList);
            // 通过权限id列表查询权限信息
            List<AuthPermission> permissionList = authPermissionService.queryByPermisionIdList(permissionIdList);
            if (CollectionUtils.isEmpty(permissionList)) {
                throw new NotFoundDomainException(ExceptionCode.PERMISSION_NOT_FOUND, "该用户未分配权限");
            }
            redisUtil.set(permissionKey, new Gson().toJson(permissionList));

            // 返回结果
            return permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }

        // 如果从redis中拿到了value,将json字符串转换为AuthPermissionList
        List<AuthPermission> permissionList = new Gson().fromJson(permissionValue,
                new TypeToken<List<AuthPermission>>() {
                }.getType());
        // 将AuthPermissionList转换为stringList
        authList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());

        // 返回结果
        return authList;
    }
}
